﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Fusion
{
	/// <summary>  Image class, stores pointer to texture, with smart reloading </summary>
	public class Image
	{
		#region Fields

		bool needsReload = true;
		private Texture2D texture;
		public Texture2D Texture
		{
			get
			{
				// Reload texture if nessecary
				if( needsReload == true )
				{
					texture = Engine.Textures.Get( filename );
					needsReload = false;
				}

				return texture;
			}
		}


		private string filename = "";
		public string Name
		{
			set
			{
				// Don't do anything if the name is the same
				if( value == filename )
					return;

				// Ensure this new texture actually exists
				Texture2D newTexture = Engine.Textures.Get( value );
				if( newTexture == null )
					return;

				// Assign the new texture
				filename = value;
				texture = newTexture;

				// Reload the texture
				if( Reloaded != null )
					Reloaded();
			}
			get { return filename; }
		}

		public int Width
		{
			get
			{
				if( texture != null )
					return texture.Width;
				else
					return 0;
			}
		}
		public int Height
		{
			get
			{
				if( texture != null )
					return texture.Height;
				else
					return 0;
			}
		}
		public Vector2 Dimensions
		{ get { return new Vector2( Width, Height ); } }

		public VoidDelegate Reloaded;

		#endregion

		/// <summary> Reload the texture if it's been changed </summary>
		private void TextureChanged( string ChangedName )
		{
			if( ChangedName == filename )
				needsReload = true;
		}


		public Image()
		{
			Engine.Textures.Changed += TextureChanged;
		}

		public Image( string TextureName )
		{
			Name = TextureName;
			Engine.Textures.Changed += TextureChanged;
		}


		public void Draw( Vector2 position, Vector2 size )
		{
			Rectangle dest = new Rectangle( (int)position.X, (int)position.Y, (int)size.X, (int)size.Y );
			Engine.spriteBatch.Draw( texture, dest, Color.White );
		}

		public void DrawCentered( Vector2 position, Vector2 size )
		{
			Rectangle dest = new Rectangle( (int)(position.X - (size.X/2)), (int)(position.Y - (size.Y/2)), (int)size.X, (int)size.Y );
			Engine.spriteBatch.Draw( texture, dest, Color.White );
		}
	}
}
